package com.ibm.risk.irmp.base.file.service.impl;

import com.ibm.risk.irmp.base.file.dao.AttachRepository;
import com.ibm.risk.irmp.base.file.entity.Attach;
import com.ibm.risk.irmp.base.file.service.AttachService;
import com.ibm.risk.irmp.base.file.service.FileStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;

@Service
@Primary
@Transactional
public class AttachServiceImpl implements AttachService {

	@Autowired
	AttachRepository attachRepository;
	@Autowired
	FileStoreService fileStore;

	@Override
	public Attach saveAttach(String origFileName, String group, File file) {
		Attach attach = new Attach();
		attach.setFileName(origFileName);
		attach.setGroupCode(group);
        try {
            String fileUri = fileStore.upload(file, group, origFileName);
			attach.setUri(fileUri);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
		return attachRepository.save(attach);
	}

	@Override
	@Transactional(readOnly = true)
	public Attach getAttachInfo(Long fileId) {
		return attachRepository.findById(fileId).get();
	}

	@Override
	@Transactional(readOnly = true)
	public Attach downloadAttach(Long fileId, File localFile) {
		Attach attach = attachRepository.findById(fileId).get();
		try {
			fileStore.download(attach.getUri(), localFile);
		} catch (Exception e) {
            throw new RuntimeException(e);
        }
		return attach;
    }
	public void deleteAttach(Long fileId) {
		attachRepository.findById(fileId).ifPresent(attach -> {
			try {
				fileStore.delete(attach.getUri());
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		});
		attachRepository.deleteById(fileId);
	}
}
